/*
 *  Getris -- A Tetris game written in Groovy.
 *  Copyright (C) 2008 Johnny Jian
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package cn.johnnyjian.getris.game

abstract class Quadrel implements Cloneable {

	def rotated = null

	def preRotate() {
		rotated = clone()
		rotated.squares = new boolean[width][height]

		// rotate the matrix
		squares.eachWithIndex { row, y ->
			row.eachWithIndex { square, x ->
				rotated.squares[x][rotated.width - 1 - y] = square
			}
		}

		// adjust the offset
		rotated.offset = [
			left: bound - height - offset.top,
			top: offset.left
		]

		return rotated
	}

	def rotate() {
		if (rotated == null) {
			preRotate()
		}

		squares = rotated.squares
		offset = rotated.offset

		rotated = null

		return this
	}

	private copyOrRemove = { square, container, x, y ->
		eachSquare { xb, yb ->
			container.setSquareAt x + xb, y + yb, square
		}
	}

	def copyTo = copyOrRemove.curry(true)

	def removeFrom = copyOrRemove.curry(false)

	/**
	 * Checks if the position at (x, y) is a square.
	 * The position is relative to the left-top of the bounds, instead of the offset.
	 */
	def isSquareAt(x, y) {
		if (x in left..right && y in top..bottom) {
			return squares[y - offset.top][x - offset.left]
		} else {
			return false
		}
	}

	/**
	 * Iterates all the squares in this quadrel.
	 * Only the position with square will be iterated.
	 */
	def eachSquare(Closure closure) {
		closure.delegate = this
		squares.eachWithIndex { row, y ->
			row.eachWithIndex { square, x ->
				if (square) {
					closure(x + offset.left, y + offset.top)
				}
			}
		}
	}

	def getHeight() {
		squares.size()
	}

	def getWidth() {
		squares[0].size()
	}

	def getLeft() {
		offset.left
	}

	def getRight() {
		offset.left + width - 1
	}

	def getTop() {
		offset.top
	}

	def getBottom() {
		offset.top + height - 1
	}

}
